package com.mexico.inloancash.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.mexico.inloancash.MyApplication;
import com.mexico.inloancash.R;
import com.mexico.inloancash.adapter.IndiaCouponAdapter;
import com.mexico.inloancash.bean.India_Billing_ListBean;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.mexico.inloancash.utils.MyToast;
import com.mingle.widget.LoadingView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 优惠卷
 */
public class IndiaDiscount_Activity extends BaseActivity {

    @BindView(R.id.logon_back)
    ImageView mIndia_GonBack;

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.bill_recycle)
    RecyclerView mIndiaRecyclerView;

    @BindView(R.id.refresh)
    SwipeRefreshLayout mIndiaSwipeRefreshLayout;

    @BindView(R.id.empty_linear)
    LinearLayout mIndiaEmpty_Layout;

    @BindView(R.id.loadView)
    LoadingView mIndiaLoading_View;

    @BindView(R.id.data_linear)
    LinearLayout mIndiaData_Layout;

    private int page = 1;
    private int limit = 10;
    private Handler handler = new Handler();
    private boolean isFresh = false;//判断是否有分页,false有分页数据，true没有分页数据
    private List<India_Billing_ListBean.DataBean> list;
    private IndiaCouponAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.india_activity_view_coupon);
        ButterKnife.bind(this);
        title.setText("Coupons");
        list = new ArrayList<>();
        adapter = new IndiaCouponAdapter();
        mIndiaSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mIndiaSwipeRefreshLayout.setColorSchemeResources(R.color.theme);
        mIndiaSwipeRefreshLayout.setRefreshing(false);
        mIndiaSwipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mIndiaSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mIndiaLessening();
                    }
                }, 1000);
            }
        });
        mIndiaSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mIndiaSwipeRefreshLayout.setRefreshing(false);
            }
        });
        mIndiaRecyclerView.setAdapter(adapter);
        mIndiaRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        if (!isFresh) {
                            page += 1;
                            mIndiaPull_MyBill(false);
                        } else {
                            MyToast.show(IndiaDiscount_Activity.this, "All content has been accessed");
                        }
                    }
                }
            }
        });
        mIndiaLessening();
    }

    //数据还原
    public void mIndiaLessening() {
        page = 1;
        mIndiaPull_MyBill(true);
    }

    @OnClick(R.id.logon_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取订单信息
     */
    public void mIndiaPull_MyBill(boolean isRefresh) {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getBill = api.getBill(MyPreferencesManager.getString("token", ""), MyApplication.source);
        getBill.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    if (response.isSuccessful()) {
                        India_Billing_ListBean indiaBillingListBean = new Gson().fromJson(response.body(), India_Billing_ListBean.class);
                        if (indiaBillingListBean.getCode() == 200) {
                            if (isRefresh) {
                                list.clear();
                            }
                            if (indiaBillingListBean.getData().size() < limit) {
                                isFresh = true;
                            }

                            list.addAll(filter(indiaBillingListBean.getData()));
                            adapter.setNewData(list);
                            if (list.size() > 0) {
                                mIndiaEmpty_Layout.setVisibility(View.GONE);
                                mIndiaSwipeRefreshLayout.setVisibility(View.VISIBLE);
                            } else {
                                mIndiaEmpty_Layout.setVisibility(View.VISIBLE);
                                mIndiaSwipeRefreshLayout.setVisibility(View.GONE);
                            }
                        } else if (indiaBillingListBean.getCode() == 401) {
                            Intent intent = new Intent(IndiaDiscount_Activity.this, IndiaLoginActivity.class);
                            startActivity(intent);
                        }
                    }
                } catch (Exception e) {

                }
                mIndiaSwipeRefreshLayout.setRefreshing(false);
                mIndiaLoading_View.setVisibility(View.GONE);
                mIndiaData_Layout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                mIndiaSwipeRefreshLayout.setRefreshing(false);
                mIndiaLoading_View.setVisibility(View.GONE);
                mIndiaData_Layout.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 过滤数据， 只显示优惠卷
     *
     * @param list
     * @return
     */
    private List<India_Billing_ListBean.DataBean> filter(List<India_Billing_ListBean.DataBean> list) {
        List<India_Billing_ListBean.DataBean> data = new ArrayList<>();
        for (India_Billing_ListBean.DataBean item : list) {
            if (item.isCoupon()) {
                data.add(item);
            }
        }
        return data;
    }
}
